using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GomokuGame.AI
{
    /// <summary>
    /// 专家AI - 高级五子棋战术算法
    /// </summary>
    public class ExpertAI : IAIAlgorithm
    {
        private readonly Random random = new Random();
        private int thinkingProgress = 0;
        private DateTime startTime;
        private int maxThinkingTime;
        private int nodesEvaluated = 0;
        private int searchDepth = 6;

        // 战术模式权重
        private readonly Dictionary<string, double> tacticalPatterns;
        private readonly Dictionary<string, double> threatCombinations;

        public AIDifficulty Difficulty => AIDifficulty.Expert;
        public string Name => "专家AI";

        public ExpertAI()
        {
            // 初始化战术模式权重
            tacticalPatterns = InitializeTacticalPatterns();
            threatCombinations = InitializeThreatCombinations();
        }

        public async Task<Move> CalculateNextMoveAsync(PieceType[,] board, PieceType currentPlayer, int maxThinkingTime = 5000)
        {
            return await Task.Run(() => CalculateNextMove(board, currentPlayer, maxThinkingTime));
        }

        public Move CalculateNextMove(PieceType[,] board, PieceType currentPlayer, int maxThinkingTime = 5000)
        {
            startTime = DateTime.Now;
            this.maxThinkingTime = maxThinkingTime;
            thinkingProgress = 0;
            nodesEvaluated = 0;

            // 获取所有可用的空位置
            var availableMoves = GetAvailableMoves(board);
            
            if (availableMoves.Count == 0)
                return null;

            // 开局阶段：使用高级开局库
            if (IsOpeningPhase(board))
            {
                var openingMove = GetAdvancedOpeningMove(board, currentPlayer);
                if (openingMove.Row >= 0 && openingMove.Col >= 0)
                {
                    return new Move(openingMove.Row, openingMove.Col, currentPlayer, 1000, 100);
                }
            }

            // 使用迭代加深搜索
            Move bestMove = null;
            double bestScore = double.MinValue;
            int maxDepth = searchDepth;

            for (int depth = 3; depth <= maxDepth; depth++)
            {
                if (IsTimeUp()) break;

                var currentBestMove = FindBestMove(board, availableMoves, currentPlayer, depth);
                if (currentBestMove != null)
                {
                    bestMove = currentBestMove;
                    thinkingProgress = (depth - 2) * 100 / (maxDepth - 2);
                }
            }

            var thinkingTime = (int)(DateTime.Now - startTime).TotalMilliseconds;
            thinkingProgress = 100;

            return bestMove ?? new Move(availableMoves[0].Row, availableMoves[0].Col, currentPlayer, 0, thinkingTime);
        }

        public int GetThinkingProgress()
        {
            return thinkingProgress;
        }

        public void Reset()
        {
            thinkingProgress = 0;
            nodesEvaluated = 0;
        }

        /// <summary>
        /// 初始化战术模式权重
        /// </summary>
        private Dictionary<string, double> InitializeTacticalPatterns()
        {
            return new Dictionary<string, double>
            {
                // 基本战术模式
                {"LiveFour", 10000},           // 活四
                {"SleepFour", 5000},           // 眠四
                {"LiveThree", 1000},           // 活三
                {"SleepThree", 500},           // 眠三
                {"LiveTwo", 100},              // 活二
                {"SleepTwo", 50},              // 眠二
                
                // 高级战术模式
                {"DoubleLiveThree", 5000},     // 双活三
                {"LiveThreeSleepThree", 3000}, // 活三眠三
                {"DoubleSleepFour", 8000},     // 双眠四
                {"CrossPattern", 2000},        // 十字形
                {"TrianglePattern", 1500},     // 三角形
                {"LPattern", 1200},            // L形
                
                // 特殊战术
                {"Fork", 3000},                // 分叉
                {"Blocking", 800},             // 阻挡
                {"Extension", 600},            // 延伸
                {"Connection", 400}            // 连接
            };
        }

        /// <summary>
        /// 初始化威胁组合权重
        /// </summary>
        private Dictionary<string, double> InitializeThreatCombinations()
        {
            return new Dictionary<string, double>
            {
                {"LiveFour_Any", 100000},      // 活四+任意
                {"DoubleLiveThree", 50000},    // 双活三
                {"LiveThree_SleepFour", 30000}, // 活三+眠四
                {"TripleLiveThree", 40000},    // 三活三
                {"MultipleSleepFour", 25000}   // 多眠四
            };
        }

        /// <summary>
        /// 使用Alpha-Beta剪枝找到最佳移动
        /// </summary>
        private Move FindBestMove(PieceType[,] board, List<Position> availableMoves, PieceType currentPlayer, int depth)
        {
            Move bestMove = null;
            double bestScore = double.MinValue;
            double alpha = double.MinValue;
            double beta = double.MaxValue;

            // 对移动进行高级排序
            var sortedMoves = SortMovesByAdvancedThreat(board, availableMoves, currentPlayer);

            foreach (var move in sortedMoves)
            {
                if (IsTimeUp()) break;

                // 临时放置棋子
                board[move.Row, move.Col] = currentPlayer;

                // 计算分数
                double score = AlphaBeta(board, depth - 1, alpha, beta, false, currentPlayer);

                // 恢复棋盘
                board[move.Row, move.Col] = PieceType.Empty;

                // 更新最佳移动
                if (score > bestScore)
                {
                    bestScore = score;
                    bestMove = new Move(move.Row, move.Col, currentPlayer, score);
                }

                alpha = Math.Max(alpha, bestScore);
            }

            return bestMove;
        }

        /// <summary>
        /// Alpha-Beta剪枝算法
        /// </summary>
        private double AlphaBeta(PieceType[,] board, int depth, double alpha, double beta, bool isMaximizing, PieceType currentPlayer)
        {
            nodesEvaluated++;

            if (IsTimeUp()) return 0;

            if (IsGameOver(board))
            {
                return EvaluateBoardAdvanced(board, currentPlayer);
            }

            if (depth == 0)
            {
                return EvaluateBoardAdvanced(board, currentPlayer);
            }

            var availableMoves = GetAvailableMoves(board);
            if (availableMoves.Count == 0)
            {
                return EvaluateBoardAdvanced(board, currentPlayer);
            }

            if (isMaximizing)
            {
                double maxScore = double.MinValue;
                var sortedMoves = SortMovesByAdvancedThreat(board, availableMoves, currentPlayer);
                
                foreach (var move in sortedMoves)
                {
                    board[move.Row, move.Col] = currentPlayer;
                    double score = AlphaBeta(board, depth - 1, alpha, beta, false, currentPlayer);
                    board[move.Row, move.Col] = PieceType.Empty;

                    maxScore = Math.Max(maxScore, score);
                    alpha = Math.Max(alpha, score);

                    if (beta <= alpha)
                        break;
                }
                return maxScore;
            }
            else
            {
                double minScore = double.MaxValue;
                var opponent = currentPlayer == PieceType.Black ? PieceType.White : PieceType.Black;
                var sortedMoves = SortMovesByAdvancedThreat(board, availableMoves, opponent);
                
                foreach (var move in sortedMoves)
                {
                    board[move.Row, move.Col] = opponent;
                    double score = AlphaBeta(board, depth - 1, alpha, beta, true, currentPlayer);
                    board[move.Row, move.Col] = PieceType.Empty;

                    minScore = Math.Min(minScore, score);
                    beta = Math.Min(beta, score);

                    if (beta <= alpha)
                        break;
                }
                return minScore;
            }
        }

        /// <summary>
        /// 根据高级威胁程度对移动进行排序
        /// </summary>
        private List<Position> SortMovesByAdvancedThreat(PieceType[,] board, List<Position> moves, PieceType player)
        {
            var scoredMoves = moves.Select(move => new
            {
                Position = move,
                Score = EvaluateAdvancedThreat(board, move, player)
            }).OrderByDescending(x => x.Score).ToList();

            return scoredMoves.Select(x => x.Position).ToList();
        }

        /// <summary>
        /// 评估高级威胁
        /// </summary>
        private double EvaluateAdvancedThreat(PieceType[,] board, Position move, PieceType player)
        {
            double threat = 0;
            var opponent = player == PieceType.Black ? PieceType.White : PieceType.Black;

            // 临时放置棋子
            board[move.Row, move.Col] = player;

            // 检查是否能获胜
            if (CheckWin(board, move.Row, move.Col, player))
            {
                threat += 100000;
            }

            // 检查是否能阻止对手获胜
            board[move.Row, move.Col] = opponent;
            if (CheckWin(board, move.Row, move.Col, opponent))
            {
                threat += 50000;
            }

            // 恢复空位置
            board[move.Row, move.Col] = PieceType.Empty;

            // 评估战术模式
            threat += EvaluateTacticalPatterns(board, move, player);

            // 评估威胁组合
            threat += EvaluateThreatCombinations(board, move, player);

            // 评估局势控制
            threat += EvaluatePositionalControl(board, move, player);

            return threat;
        }

        /// <summary>
        /// 评估战术模式
        /// </summary>
        private double EvaluateTacticalPatterns(PieceType[,] board, Position move, PieceType player)
        {
            double score = 0;
            var patterns = AnalyzeTacticalPatterns(board, move, player);

            foreach (var pattern in patterns)
            {
                if (tacticalPatterns.ContainsKey(pattern))
                {
                    score += tacticalPatterns[pattern];
                }
            }

            return score;
        }

        /// <summary>
        /// 分析战术模式
        /// </summary>
        private List<string> AnalyzeTacticalPatterns(PieceType[,] board, Position move, PieceType player)
        {
            var patterns = new List<string>();
            var directions = new[] { (0, 1), (1, 0), (1, 1), (1, -1) };

            // 临时放置棋子
            board[move.Row, move.Col] = player;

            // 分析每个方向的模式
            foreach (var (dr, dc) in directions)
            {
                var lineAnalysis = AnalyzeLineAdvanced(board, move, dr, dc, player);
                
                if (lineAnalysis.LiveFour) patterns.Add("LiveFour");
                if (lineAnalysis.SleepFour) patterns.Add("SleepFour");
                if (lineAnalysis.LiveThree) patterns.Add("LiveThree");
                if (lineAnalysis.SleepThree) patterns.Add("SleepThree");
                if (lineAnalysis.LiveTwo) patterns.Add("LiveTwo");
                if (lineAnalysis.SleepTwo) patterns.Add("SleepTwo");
            }

            // 分析特殊模式
            if (HasCrossPattern(board, move, player)) patterns.Add("CrossPattern");
            if (HasTrianglePattern(board, move, player)) patterns.Add("TrianglePattern");
            if (HasLPattern(board, move, player)) patterns.Add("LPattern");
            if (HasForkPattern(board, move, player)) patterns.Add("Fork");

            // 恢复空位置
            board[move.Row, move.Col] = PieceType.Empty;

            return patterns;
        }

        /// <summary>
        /// 评估威胁组合
        /// </summary>
        private double EvaluateThreatCombinations(PieceType[,] board, Position move, PieceType player)
        {
            double score = 0;
            var combinations = AnalyzeThreatCombinations(board, move, player);

            foreach (var combination in combinations)
            {
                if (threatCombinations.ContainsKey(combination))
                {
                    score += threatCombinations[combination];
                }
            }

            return score;
        }

        /// <summary>
        /// 分析威胁组合
        /// </summary>
        private List<string> AnalyzeThreatCombinations(PieceType[,] board, Position move, PieceType player)
        {
            var combinations = new List<string>();
            var directions = new[] { (0, 1), (1, 0), (1, 1), (1, -1) };

            // 临时放置棋子
            board[move.Row, move.Col] = player;

            int liveFourCount = 0;
            int liveThreeCount = 0;
            int sleepFourCount = 0;

            foreach (var (dr, dc) in directions)
            {
                var lineAnalysis = AnalyzeLineAdvanced(board, move, dr, dc, player);
                
                if (lineAnalysis.LiveFour) liveFourCount++;
                if (lineAnalysis.LiveThree) liveThreeCount++;
                if (lineAnalysis.SleepFour) sleepFourCount++;
            }

            // 检查威胁组合
            if (liveFourCount > 0) combinations.Add("LiveFour_Any");
            if (liveThreeCount >= 2) combinations.Add("DoubleLiveThree");
            if (liveThreeCount >= 3) combinations.Add("TripleLiveThree");
            if (liveThreeCount >= 1 && sleepFourCount >= 1) combinations.Add("LiveThree_SleepFour");
            if (sleepFourCount >= 2) combinations.Add("MultipleSleepFour");

            // 恢复空位置
            board[move.Row, move.Col] = PieceType.Empty;

            return combinations;
        }

        /// <summary>
        /// 评估局势控制
        /// </summary>
        private double EvaluatePositionalControl(PieceType[,] board, Position move, PieceType player)
        {
            double score = 0;
            int boardSize = board.GetLength(0);
            int center = boardSize / 2;

            // 中心控制
            int distanceFromCenter = Math.Abs(move.Row - center) + Math.Abs(move.Col - center);
            score += (boardSize - distanceFromCenter) * 20;

            // 连接价值
            score += EvaluateConnectionValue(board, move, player);

            // 扩展价值
            score += EvaluateExtensionValue(board, move, player);

            // 阻挡价值
            score += EvaluateBlockingValue(board, move, player);

            return score;
        }

        /// <summary>
        /// 评估连接价值
        /// </summary>
        private double EvaluateConnectionValue(PieceType[,] board, Position move, PieceType player)
        {
            double score = 0;
            int boardSize = board.GetLength(0);

            // 检查是否能连接己方棋子
            for (int dr = -2; dr <= 2; dr++)
            {
                for (int dc = -2; dc <= 2; dc++)
                {
                    if (dr == 0 && dc == 0) continue;

                    int newRow = move.Row + dr;
                    int newCol = move.Col + dc;

                    if (newRow >= 0 && newRow < boardSize && newCol >= 0 && newCol < boardSize)
                    {
                        if (board[newRow, newCol] == player)
                        {
                            score += 100 / (Math.Abs(dr) + Math.Abs(dc)); // 距离越近价值越高
                        }
                    }
                }
            }

            return score;
        }

        /// <summary>
        /// 评估扩展价值
        /// </summary>
        private double EvaluateExtensionValue(PieceType[,] board, Position move, PieceType player)
        {
            double score = 0;
            var directions = new[] { (0, 1), (1, 0), (1, 1), (1, -1) };

            // 临时放置棋子
            board[move.Row, move.Col] = player;

            foreach (var (dr, dc) in directions)
            {
                var lineAnalysis = AnalyzeLineAdvanced(board, move, dr, dc, player);
                
                // 扩展现有连子
                if (lineAnalysis.LiveThree || lineAnalysis.SleepFour)
                {
                    score += 500;
                }
            }

            // 恢复空位置
            board[move.Row, move.Col] = PieceType.Empty;

            return score;
        }

        /// <summary>
        /// 评估阻挡价值
        /// </summary>
        private double EvaluateBlockingValue(PieceType[,] board, Position move, PieceType player)
        {
            double score = 0;
            var opponent = player == PieceType.Black ? PieceType.White : PieceType.Black;
            var directions = new[] { (0, 1), (1, 0), (1, 1), (1, -1) };

            // 临时放置棋子
            board[move.Row, move.Col] = player;

            foreach (var (dr, dc) in directions)
            {
                var lineAnalysis = AnalyzeLineAdvanced(board, move, dr, dc, opponent);
                
                // 阻挡对手威胁
                if (lineAnalysis.LiveFour) score += 10000;
                if (lineAnalysis.SleepFour) score += 5000;
                if (lineAnalysis.LiveThree) score += 1000;
            }

            // 恢复空位置
            board[move.Row, move.Col] = PieceType.Empty;

            return score;
        }

        /// <summary>
        /// 高级连线分析
        /// </summary>
        private LineAnalysisAdvanced AnalyzeLineAdvanced(PieceType[,] board, Position pos, int dr, int dc, PieceType player)
        {
            var analysis = new LineAnalysisAdvanced();
            int boardSize = board.GetLength(0);

            // 临时放置棋子
            board[pos.Row, pos.Col] = player;

            // 计算连续棋子
            int forwardCount = CountInDirection(board, pos.Row, pos.Col, dr, dc, player);
            int backwardCount = CountInDirection(board, pos.Row, pos.Col, -dr, -dc, player);
            int totalCount = forwardCount + backwardCount - 1;

            // 检查两端是否被封堵
            bool forwardBlocked = IsBlocked(board, pos.Row + dr * forwardCount, pos.Col + dc * forwardCount);
            bool backwardBlocked = IsBlocked(board, pos.Row - dr * backwardCount, pos.Col - dc * backwardCount);

            // 计算活棋和眠棋
            if (totalCount >= 5)
            {
                analysis.ThreatValue = 100000;
            }
            else if (totalCount == 4)
            {
                if (!forwardBlocked && !backwardBlocked)
                {
                    analysis.ThreatValue = 10000;
                    analysis.LiveFour = true;
                }
                else if (!forwardBlocked || !backwardBlocked)
                {
                    analysis.ThreatValue = 5000;
                    analysis.SleepFour = true;
                }
            }
            else if (totalCount == 3)
            {
                if (!forwardBlocked && !backwardBlocked)
                {
                    analysis.ThreatValue = 1000;
                    analysis.LiveThree = true;
                }
                else if (!forwardBlocked || !backwardBlocked)
                {
                    analysis.ThreatValue = 500;
                    analysis.SleepThree = true;
                }
            }
            else if (totalCount == 2)
            {
                if (!forwardBlocked && !backwardBlocked)
                {
                    analysis.ThreatValue = 100;
                    analysis.LiveTwo = true;
                }
                else if (!forwardBlocked || !backwardBlocked)
                {
                    analysis.ThreatValue = 50;
                    analysis.SleepTwo = true;
                }
            }

            // 恢复空位置
            board[pos.Row, pos.Col] = PieceType.Empty;

            return analysis;
        }

        /// <summary>
        /// 检查是否有十字形模式
        /// </summary>
        private bool HasCrossPattern(PieceType[,] board, Position move, PieceType player)
        {
            var directions = new[] { (0, 1), (1, 0), (1, 1), (1, -1) };
            int activeDirections = 0;

            foreach (var (dr, dc) in directions)
            {
                var lineAnalysis = AnalyzeLineAdvanced(board, move, dr, dc, player);
                if (lineAnalysis.LiveTwo || lineAnalysis.LiveThree || lineAnalysis.LiveFour)
                {
                    activeDirections++;
                }
            }

            return activeDirections >= 2;
        }

        /// <summary>
        /// 检查是否有三角形模式
        /// </summary>
        private bool HasTrianglePattern(PieceType[,] board, Position move, PieceType player)
        {
            // 简化的三角形模式检测
            int boardSize = board.GetLength(0);
            int connections = 0;

            for (int dr = -1; dr <= 1; dr++)
            {
                for (int dc = -1; dc <= 1; dc++)
                {
                    if (dr == 0 && dc == 0) continue;

                    int newRow = move.Row + dr;
                    int newCol = move.Col + dc;

                    if (newRow >= 0 && newRow < boardSize && newCol >= 0 && newCol < boardSize)
                    {
                        if (board[newRow, newCol] == player)
                        {
                            connections++;
                        }
                    }
                }
            }

            return connections >= 3;
        }

        /// <summary>
        /// 检查是否有L形模式
        /// </summary>
        private bool HasLPattern(PieceType[,] board, Position move, PieceType player)
        {
            // 简化的L形模式检测
            var directions = new[] { (0, 1), (1, 0) };
            int activeDirections = 0;

            foreach (var (dr, dc) in directions)
            {
                var lineAnalysis = AnalyzeLineAdvanced(board, move, dr, dc, player);
                if (lineAnalysis.LiveTwo || lineAnalysis.LiveThree)
                {
                    activeDirections++;
                }
            }

            return activeDirections >= 2;
        }

        /// <summary>
        /// 检查是否有分叉模式
        /// </summary>
        private bool HasForkPattern(PieceType[,] board, Position move, PieceType player)
        {
            var directions = new[] { (0, 1), (1, 0), (1, 1), (1, -1) };
            int liveThreeCount = 0;
            int liveFourCount = 0;

            foreach (var (dr, dc) in directions)
            {
                var lineAnalysis = AnalyzeLineAdvanced(board, move, dr, dc, player);
                if (lineAnalysis.LiveThree) liveThreeCount++;
                if (lineAnalysis.LiveFour) liveFourCount++;
            }

            return (liveThreeCount >= 2) || (liveFourCount >= 1 && liveThreeCount >= 1);
        }

        /// <summary>
        /// 检查是否为开局阶段
        /// </summary>
        private bool IsOpeningPhase(PieceType[,] board)
        {
            int pieceCount = 0;
            int boardSize = board.GetLength(0);
            
            for (int row = 0; row < boardSize; row++)
            {
                for (int col = 0; col < boardSize; col++)
                {
                    if (board[row, col] != PieceType.Empty)
                        pieceCount++;
                }
            }

            return pieceCount <= 8; // 前8手为开局
        }

        /// <summary>
        /// 获取高级开局移动
        /// </summary>
        private Position GetAdvancedOpeningMove(PieceType[,] board, PieceType currentPlayer)
        {
            int boardSize = board.GetLength(0);
            int center = boardSize / 2;

            // 第一手：天元
            if (IsFirstMove(board))
            {
                return new Position(center, center);
            }

            // 第二手：星位
            if (IsSecondMove(board))
            {
                var starPositions = new[]
                {
                    new Position(center - 3, center - 3),
                    new Position(center - 3, center + 3),
                    new Position(center + 3, center - 3),
                    new Position(center + 3, center + 3)
                };

                foreach (var pos in starPositions)
                {
                    if (board[pos.Row, pos.Col] == PieceType.Empty)
                        return pos;
                }
            }

            // 其他开局：基于战术分析
            return GetTacticalOpeningMove(board, currentPlayer);
        }

        /// <summary>
        /// 检查是否为第一手
        /// </summary>
        private bool IsFirstMove(PieceType[,] board)
        {
            int boardSize = board.GetLength(0);
            for (int row = 0; row < boardSize; row++)
            {
                for (int col = 0; col < boardSize; col++)
                {
                    if (board[row, col] != PieceType.Empty)
                        return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 检查是否为第二手
        /// </summary>
        private bool IsSecondMove(PieceType[,] board)
        {
            int pieceCount = 0;
            int boardSize = board.GetLength(0);
            
            for (int row = 0; row < boardSize; row++)
            {
                for (int col = 0; col < boardSize; col++)
                {
                    if (board[row, col] != PieceType.Empty)
                        pieceCount++;
                }
            }

            return pieceCount == 1;
        }

        /// <summary>
        /// 获取战术开局移动
        /// </summary>
        private Position GetTacticalOpeningMove(PieceType[,] board, PieceType currentPlayer)
        {
            var availableMoves = GetAvailableMoves(board);
            var tacticalMoves = new List<Position>();

            foreach (var move in availableMoves)
            {
                if (HasNearbyPieces(board, move) && HasTacticalPotential(board, move, currentPlayer))
                {
                    tacticalMoves.Add(move);
                }
            }

            if (tacticalMoves.Count > 0)
            {
                return tacticalMoves[random.Next(tacticalMoves.Count)];
            }

            return availableMoves[random.Next(availableMoves.Count)];
        }

        /// <summary>
        /// 检查位置附近是否有棋子
        /// </summary>
        private bool HasNearbyPieces(PieceType[,] board, Position position)
        {
            int boardSize = board.GetLength(0);
            
            for (int row = Math.Max(0, position.Row - 2); row <= Math.Min(boardSize - 1, position.Row + 2); row++)
            {
                for (int col = Math.Max(0, position.Col - 2); col <= Math.Min(boardSize - 1, position.Col + 2); col++)
                {
                    if (board[row, col] != PieceType.Empty)
                        return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 检查是否有战术潜力
        /// </summary>
        private bool HasTacticalPotential(PieceType[,] board, Position move, PieceType player)
        {
            var directions = new[] { (0, 1), (1, 0), (1, 1), (1, -1) };
            int potentialDirections = 0;

            foreach (var (dr, dc) in directions)
            {
                var lineAnalysis = AnalyzeLineAdvanced(board, move, dr, dc, player);
                if (lineAnalysis.LiveTwo || lineAnalysis.LiveThree)
                {
                    potentialDirections++;
                }
            }

            return potentialDirections >= 1;
        }

        /// <summary>
        /// 高级棋盘评估
        /// </summary>
        private double EvaluateBoardAdvanced(PieceType[,] board, PieceType currentPlayer)
        {
            double score = 0;
            int boardSize = board.GetLength(0);
            var opponent = currentPlayer == PieceType.Black ? PieceType.White : PieceType.Black;

            // 检查获胜条件
            for (int row = 0; row < boardSize; row++)
            {
                for (int col = 0; col < boardSize; col++)
                {
                    if (board[row, col] == currentPlayer)
                    {
                        if (CheckWin(board, row, col, currentPlayer))
                            return 100000;
                    }
                    else if (board[row, col] == opponent)
                    {
                        if (CheckWin(board, row, col, opponent))
                            return -100000;
                    }
                }
            }

            // 评估连子情况
            score += EvaluateLinesAdvanced(board, currentPlayer);
            score -= EvaluateLinesAdvanced(board, opponent);

            // 评估位置控制
            score += EvaluatePositionalControlAdvanced(board, currentPlayer);
            score -= EvaluatePositionalControlAdvanced(board, opponent);

            // 评估战术优势
            score += EvaluateTacticalAdvantage(board, currentPlayer);
            score -= EvaluateTacticalAdvantage(board, opponent);

            return score;
        }

        /// <summary>
        /// 高级连子评估
        /// </summary>
        private double EvaluateLinesAdvanced(PieceType[,] board, PieceType player)
        {
            double score = 0;
            int boardSize = board.GetLength(0);

            for (int row = 0; row < boardSize; row++)
            {
                for (int col = 0; col < boardSize; col++)
                {
                    if (board[row, col] == player)
                    {
                        var directions = new[] { (0, 1), (1, 0), (1, 1), (1, -1) };

                        foreach (var (dr, dc) in directions)
                        {
                            var analysis = AnalyzeLineAdvanced(board, new Position(row, col), dr, dc, player);
                            score += analysis.ThreatValue;
                        }
                    }
                }
            }

            return score;
        }

        /// <summary>
        /// 高级位置控制评估
        /// </summary>
        private double EvaluatePositionalControlAdvanced(PieceType[,] board, PieceType player)
        {
            double score = 0;
            int boardSize = board.GetLength(0);
            int center = boardSize / 2;

            for (int row = 0; row < boardSize; row++)
            {
                for (int col = 0; col < boardSize; col++)
                {
                    if (board[row, col] == player)
                    {
                        // 中心位置更有价值
                        int distanceFromCenter = Math.Abs(row - center) + Math.Abs(col - center);
                        score += (boardSize - distanceFromCenter) * 10;

                        // 连接价值
                        score += EvaluateConnectionValue(board, new Position(row, col), player);
                    }
                }
            }

            return score;
        }

        /// <summary>
        /// 评估战术优势
        /// </summary>
        private double EvaluateTacticalAdvantage(PieceType[,] board, PieceType player)
        {
            double score = 0;
            int boardSize = board.GetLength(0);

            // 计算战术模式数量
            int liveFourCount = 0;
            int liveThreeCount = 0;
            int sleepFourCount = 0;

            for (int row = 0; row < boardSize; row++)
            {
                for (int col = 0; col < boardSize; col++)
                {
                    if (board[row, col] == player)
                    {
                        var directions = new[] { (0, 1), (1, 0), (1, 1), (1, -1) };

                        foreach (var (dr, dc) in directions)
                        {
                            var analysis = AnalyzeLineAdvanced(board, new Position(row, col), dr, dc, player);
                            if (analysis.LiveFour) liveFourCount++;
                            if (analysis.LiveThree) liveThreeCount++;
                            if (analysis.SleepFour) sleepFourCount++;
                        }
                    }
                }
            }

            // 根据战术模式给分
            score += liveFourCount * 10000;
            score += liveThreeCount * 1000;
            score += sleepFourCount * 500;

            return score;
        }

        /// <summary>
        /// 检查是否获胜
        /// </summary>
        private bool CheckWin(PieceType[,] board, int row, int col, PieceType pieceType)
        {
            if (CountInDirection(board, row, col, 0, 1, pieceType) + CountInDirection(board, row, col, 0, -1, pieceType) - 1 >= 5)
                return true;

            if (CountInDirection(board, row, col, 1, 0, pieceType) + CountInDirection(board, row, col, -1, 0, pieceType) - 1 >= 5)
                return true;

            if (CountInDirection(board, row, col, 1, 1, pieceType) + CountInDirection(board, row, col, -1, -1, pieceType) - 1 >= 5)
                return true;

            if (CountInDirection(board, row, col, 1, -1, pieceType) + CountInDirection(board, row, col, -1, 1, pieceType) - 1 >= 5)
                return true;

            return false;
        }

        /// <summary>
        /// 在指定方向上计算连续棋子数量
        /// </summary>
        private int CountInDirection(PieceType[,] board, int row, int col, int deltaRow, int deltaCol, PieceType pieceType)
        {
            int count = 0;
            int currentRow = row;
            int currentCol = col;
            int boardSize = board.GetLength(0);

            while (currentRow >= 0 && currentRow < boardSize && currentCol >= 0 && currentCol < boardSize && 
                   board[currentRow, currentCol] == pieceType)
            {
                count++;
                currentRow += deltaRow;
                currentCol += deltaCol;
            }

            return count;
        }

        /// <summary>
        /// 获取所有可用的空位置
        /// </summary>
        private List<Position> GetAvailableMoves(PieceType[,] board)
        {
            var moves = new List<Position>();
            int boardSize = board.GetLength(0);

            for (int row = 0; row < boardSize; row++)
            {
                for (int col = 0; col < boardSize; col++)
                {
                    if (board[row, col] == PieceType.Empty)
                    {
                        moves.Add(new Position(row, col));
                    }
                }
            }

            return moves;
        }

        /// <summary>
        /// 检查是否超时
        /// </summary>
        private bool IsTimeUp()
        {
            return (DateTime.Now - startTime).TotalMilliseconds > maxThinkingTime;
        }

        /// <summary>
        /// 检查游戏是否结束
        /// </summary>
        private bool IsGameOver(PieceType[,] board)
        {
            int boardSize = board.GetLength(0);

            for (int row = 0; row < boardSize; row++)
            {
                for (int col = 0; col < boardSize; col++)
                {
                    if (board[row, col] != PieceType.Empty)
                    {
                        if (CheckWin(board, row, col, board[row, col]))
                            return true;
                    }
                }
            }

            for (int row = 0; row < boardSize; row++)
            {
                for (int col = 0; col < boardSize; col++)
                {
                    if (board[row, col] == PieceType.Empty)
                        return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 检查位置是否被封堵
        /// </summary>
        private bool IsBlocked(PieceType[,] board, int row, int col)
        {
            int boardSize = board.GetLength(0);
            return row < 0 || row >= boardSize || col < 0 || col >= boardSize || board[row, col] != PieceType.Empty;
        }

        /// <summary>
        /// 位置结构
        /// </summary>
        private struct Position
        {
            public int Row { get; set; }
            public int Col { get; set; }

            public Position(int row, int col)
            {
                Row = row;
                Col = col;
            }
        }

        /// <summary>
        /// 高级连线分析结构
        /// </summary>
        private struct LineAnalysisAdvanced
        {
            public double ThreatValue { get; set; }
            public bool LiveFour { get; set; }
            public bool SleepFour { get; set; }
            public bool LiveThree { get; set; }
            public bool SleepThree { get; set; }
            public bool LiveTwo { get; set; }
            public bool SleepTwo { get; set; }
        }
    }
} 